package org.benjamin.lending.controller;

import org.apache.commons.lang3.SerializationUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.BJUIResult;
import org.benjamin.lending.domain.GlobalForm;
import org.benjamin.lending.domain.GlobalModel;
import org.benjamin.lending.domain.entity.GlobalSetting;
import org.benjamin.lending.service.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xywenjie on 2017/6/8.
 */
@Controller
@RequestMapping("global")
public class GlobalSettingController {

    private Logger logger = LogManager.getLogger();

    @Autowired
    private SettingService settingService;

    @GetMapping("emailConfig")
    public String passwordEmail(ModelMap modelMap){
        Map<String,String> templateMap = this.settingService.getSettingCode("email");
        modelMap.addAttribute("templateMap",templateMap);
        return "template/password";
    }

    @ResponseBody
    @PostMapping("saveTemplate")
    public BJUIResult saveTemplate(GlobalModel globalModel){
        logger.info(globalModel.getGlobalForms().toString());
        GlobalSetting globalSetting = new GlobalSetting();
        globalSetting.setCode("email");
        HashMap<String,String> stringMap = new HashMap<>();
        for(GlobalForm globalForm : globalModel.getGlobalForms()){
            stringMap.put(globalForm.getCode(),globalForm.getValue());
        }
        byte[] bytes = SerializationUtils.serialize(stringMap);
        globalSetting.setTemplate(bytes);
        this.settingService.save(globalSetting);
        //this.templateService.saveOrSubmitTask(template);
        return BJUIResult.defaultSuccess();
    }
}
